#!/bin/bash
# USAGE:
#	check
# 	check setup
#	check resultFile
# 	check -p processName [filename]
#	check -j jobid
#       check productSize
#
# DESCRIPTION:
#  CHECK is an internal ADORE command. 
#  It shows the process control list from the result files.
#
#  Using the -p option it can be used to check whether a given step is
#  possible to run.  "setup" option can be used to check if ADORE can find
#  all the necessary libraries.
#
# INPUT:
#  No required inputs.
#   
#   Optional:
#     resultFile: If specified, only displays given files process control list.
#
#     -p processName: Check if ADORE can run the given doris process. This 
#     function is currently under development. If no output is shown the it is
#     OK to run the process. Otherwise error messages will hint at the problem.
#
#     -j jobid: Check if the job submitted by quejob is finished. Return 0 if finished.
#		Job Status 	Output
#		----------------------
#		Completed	0
#		Running		1
#               Exiting		2
#               Queued		3
#               Waiting		4
#               Transferred	5
#               Held 		6
#
#     setup: Check several executables and returns assistive messages if executables are missing.
#
#     productSize: Will check to see if the product size in the result file is matching the actual file.
#
# OUTPUT:
#  Shows the process control list of given result file.
#
# Example:
# check
# check -p m_readfiles; echo $?
# check setup
#
function displayProcessControl(){
  local startline=`grep -n Start_process_control ${1} | cut -f1 -d":"`
  local endline=`grep -n End_process_control ${1} | cut -f1 -d":"`

  local length=`echo ${endline} - ${startline} |bc`
  grep -A ${length} Start_process_control ${1} | grep -v "_process_control" | grep -v "NOT_USED"
}

function listProcessFlagsFromResultFiles(){
  local file1 file2 file3 files
  files="";
  if [ "${1:-undefined}" == "undefined" ]; then 
    #interferogram
    generateRandomString
    file3=${randomString}.tmp
    if [ -e ${i_resfile} ]; then
      echo -e "INTERFEROGRAM: \t\t" > ${file3}
      displayProcessControl ${i_resfile} >> ${file3}
      files+="${file3} "
    fi
    #master
    generateRandomString
    file1=${randomString}.tmp
    if [ -e ${m_resfile} ]; then
      echo -e "MASTER: \t\t" > ${file1}
      displayProcessControl ${m_resfile} >> ${file1}
      files+="${file1} "
    fi
    #slave
    generateRandomString
    file2=${randomString}.tmp
    if [ -e ${s_resfile} ];then 
      echo -e "SLAVE: \t\t" > ${file2}
      displayProcessControl ${s_resfile} >> ${file2}
      files+="${file2} "
    fi
  #  echo ";"
    if [ -n "${files}" ]; then
      eval "paste ${files}"
      rm -rf ${files}
    else
      echo "No resultfiles can be found. Are you in the correct folder? Did you do any processing yet?"
    fi
  else
    echo "${1}:"
    displayProcessControl ${1}
  fi
}

function checkProcessFlag(){
# Given a doris process name this function returns 
# 1: already processed.
# 0: ready to process
# >1: for not ready to process.
# 2: missing file 
# 3: input error

local alreadyProcessed prevProcStatus processName resFile
[ -n "${2}" ] && resFile="${2}"
case "${1}" in 
  "m_readfiles")
    processName=`pn2rs ${1}`
    [ -z "${resFile}" ] && resFile=${m_resfile}
    [ ! -e ${resFile} ] && return 0;
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "m_porbits")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs m_readfiles`
    [ -z "${resFile}" ] && resFile=${m_resfile}
    [ ! -e ${resFile} ] && echo "Error 2: File error... m_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    [ -d "${m_orbdir}" ]  && [ "${alreadyProcessed}" -eq 0 ] && return 0
    [ ! -d "${m_orbdir}" ] && echo "Error 3: Input error... m_orbdir" && return 3
    return ${alreadyProcessed}
  ;;
  "m_crop")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs m_readfiles`
    [ -z "${resFile}" ] && resFile=${m_resfile}
    [ ! -e ${resFile} ] && echo "Error 2: File error... m_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "m_simamp")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs m_crop`
    [ -z "${resFile}" ] && resFile=${m_resfile}
    [ ! -e ${resFile} ] && echo "Error 2: File error... m_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    [ -e "${sam_in_dem}" ]  && [ "${alreadyProcessed}" -eq 0 ] && return 0
    [ ! -e "${sam_in_dem}" ] && echo "Error 3: Input error... sam_in_dem" && return 3
    return ${alreadyProcessed}
  ;;
  "m_timing")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs m_simamp`
    [ -z "${resFile}" ] && resFile=${m_resfile}
    [ ! -e ${resFile} ] && echo "Error 2: File error... m_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3    
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "m_ovs")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs m_crop`
    [ -z "${resFile}" ] && resFile=${m_resfile}
    [ ! -e ${resFile} ] && echo "Error 2: File error... m_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    [ "${m_ovs_fact_azi}" -gt 1 ] && [ "${m_ovs_fact_rng}" -gt 1 ]  && [ "${alreadyProcessed}" -eq 0 ] && return 0
    [ "${m_ovs_fact_azi}" -lt 2 ] && echo "Error 3: Input error... m_ovs_fact_azi < 2" && return 3
    [ "${m_ovs_fact_rng}" -lt 2 ] && echo "Error 3: Input error... m_ovs_fact_azi < 2" && return 3
    return ${alreadyProcessed}
  ;;
  "s_readfiles")
    processName=`pn2rs ${1}`
    [ -z "${resFile}" ] && resFile=${s_resfile}
    [ ! -e ${resFile} ] && return 0;
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "s_porbits")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs s_readfiles`
    [ -z "${resFile}" ] && resFile=${s_resfile}
    [ ! -e ${resFile} ] && echo "Error 2: File error... s_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    [ -d "${s_orbdir}" ]  && [ "${alreadyProcessed}" -eq 0 ] && return 0
    [ ! -d "${s_orbdir}" ] && echo "Error 3: Input error... s_orbdir" && return 3
    return ${alreadyProcessed}
  ;;
  "s_crop")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs s_readfiles`
    [ -z "${resFile}" ] && resFile=${s_resfile}
    [ ! -e ${resFile} ] && echo "Error 2: File error... s_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "s_ovs")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs s_crop`
    [ -z "${resFile}" ] && resFile=${s_resfile}
    [ ! -e ${resFile} ] && echo "Error 2: File error... s_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    [ "${s_ovs_fact_azi}" -gt 1 ] && [ "${s_ovs_fact_rng}" -gt 1 ]  && [ "${alreadyProcessed}" -eq 0 ] && return 0
    [ "${s_ovs_fact_azi}" -lt 2 ] && echo "Error 3: Input error... s_ovs_fact_azi < 2" && return 3
    [ "${s_ovs_fact_rng}" -lt 2 ] && echo "Error 3: Input error... s_ovs_fact_azi < 2" && return 3
    return ${alreadyProcessed}
  ;;
  "coarseorb")
    processName=`pn2rs ${1}`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && return 0;
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "coarsecorr")
    processName=`pn2rs ${1}`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "m_filtazi")
    processName=`pn2rs ${1}`
    [ -z "${resFile}" ] && resFile=${m_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... m_resfile" && return 2;
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "s_filtazi")
    processName=`pn2rs ${1}`
    [ -z "${resFile}" ] && resFile=${s_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... s_resfile" && return 2;
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "fine")
    processName=`pn2rs ${1}`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "reltiming")
    processName=`pn2rs ${1}`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "demassist")
    processName=`pn2rs ${1}`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    [ -e "${dac_in_dem}" ]  && [ "${alreadyProcessed}" -eq 0 ] && return 0
    [ ! -e "${dac_in_dem}" ] && echo "Error 3: Input error... dac_in_dem" && return 3
    return ${alreadyProcessed}
  ;;
  "coregpm")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs fine`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "resample")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs coregpm`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "filtrange")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs resample`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "interfero")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs resample`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "comprefpha")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs interfero`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "subtrrefpha")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs comprefpha`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "comprefdem")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs interfero`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "subtrrefdem")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs comprefdem`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "coherence")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs interfero`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "filtphase")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs interfero`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "unwrap")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs interfero`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "dinsar")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs interfero`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    [ -e "${di_in_toposlave}" ]  && [ "${alreadyProcessed}" -eq 0 ] && return 0
    [ ! -e "${di_in_toposlave}" ] && echo "Error 3: Input error... di_in_toposlave" && return 3
    return ${alreadyProcessed}
  ;;
  "slant2h")
    processName=`pn2rs ${1}`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
  "geocode")
    processName=`pn2rs ${1}`
    prevProcessName=`pn2rs slant2h`
    [ -z "${resFile}" ] && resFile=${i_resfile}
    [ ! -e ${m_resfile} ] && echo "Error 2: File error... m_resfile" && return 2;
    [ ! -e ${s_resfile} ] && echo "Error 2: File error... s_resfile" && return 2;
    [ ! -e ${resFile} ] && echo "Error 2: File error... i_resfile" && return 2;
    prevProcStatus=`${ADORESCR}/readRes.sh ${resFile} process_control ${prevProcessName}`
    [ "${prevProcStatus}" -ne 1 ] && echo "Error 3: Input error... ${processName} requires ${prevProcessName}" && return 3            
    alreadyProcessed=`${ADORESCR}/readRes.sh ${resFile} process_control ${processName}`  
    return ${alreadyProcessed}
  ;;
esac
}

function checkJobStatus(){
#		Job Status 	Output
#		----------------------
#		Completed	0
#		Running		1
#               Exiting		2
#               Queued		3
#               Waiting		4
#               Transferred	5
#               Held 		6
#
local jobStat jobid qstatOut
jobId=${1}
qstat ${jobId} &> /dev/null #check if qstat works
qstatOut=$?
[ ${qstatOut} -ne 0 ] && return ${qstatOut}
jobStat=`qstat ${jobId}| tail -n1 | tr -s " "|cut -d" " -f5` 
if [ "${jobStat}" == "C" ]; then
  return 0
elif [ "${jobStat}" == "R" ]; then
  return 1
elif [ "${jobStat}" == "E" ]; then
  return 2
elif [ "${jobStat}" == "Q" ]; then
  return 3
elif [ "${jobStat}" == "W" ]; then
  return 4
elif [ "${jobStat}" == "T" ]; then
  return 5
elif [ "${jobStat}" == "H" ]; then
  return 6
fi  
}

function checkSetup(){
if [ $# -eq 0 ]; then
 #check if adore is in ADORESCR
 #this is not the case when adore is linked.
 [ -f "${ADORESCR}/adore" ] && echo "ADORE scripts are in: ${ADORESCR}" || (echo "ADORE scripts are not in ${ADORESCR}. Please reset ADORESCR.")
 checkExecutable "csh"
 checkExecutable "doris"
 checkExecutable "getorb"
 [ $? -ne 0 ] && bold "Please install getorb from: http://www.deos.tudelft.nl/ers/precorbs/tools/."
 checkExecutable "cpxfiddle"
 [ $? -ne 0 ] && bold "Please install SARTOOLS from DORIS package."
 checkExecutable "envisat_dump_data"
 [ $? -ne 0 ] && bold "Please install ENVISAT_TOOLS from DORIS package."
 checkExecutable "psxy"
 [ $? -ne 0 ] && bold "Please install GMT. On Ubuntu: sudo apt-get install gmt" && bold "If GMT is already installed make sure the gmt/bin directory is included in the PATH environment variable." 
 checkExecutable "gnuplot"
 [ $? -ne 0 ] && bold "Please install gnuplot. On Ubuntu: sudo apt-get install gnuplot" && bold "baselines command will not run without gnuplot." 
 checkExecutable "convert"
 [ $? -ne 0 ] && bold "Please install imagemagick. On Ubuntu: sudo apt-get install imagemagick"
 checkExecutable "gdal_translate"
 [ $? -ne 0 ] && bold "Please install gdal-bin. On Ubuntu: sudo apt-get install gdal-bin"
 if ask "Would you like me to run a test in this folder (Files will be downloaded and created. ~5min)?"; then
   test1
 fi
else
 $1
fi
}

function checkExecutable(){
pathCheck=`which ${1}`
if [ "${pathCheck:-isEmpty}" != "isEmpty" ]; then
  echo "${1} in ${pathCheck}"
else
  bold "can not find ${1}"
  return 1;
fi
}

function checkUpdates(){ 
#Download current version
mkdir -p ${tmpFolder}
wget http://adore-doris.googlecode.com/svn/trunk/version -O ${tmpFolder}/version
svn_version=`cat ${tmpFolder}/version | tr -d ".r"`  
cur_version=`cat ${ADOREFOLDER}/version | tr -d ".r"`
#compare versions
if [ ${svn_version} -gt ${cur_version} ]; then
 echo "A new version is available."
 if ask "Would you like to upgrade?"; then
  touch ${ADOREFOLDER}/version
  if [ $? -eq 0 ]; then
    svn export --force http://adore-doris.googlecode.com/svn/trunk/ ${ADOREFOLDER}
  else
    sudo svn export --force http://adore-doris.googlecode.com/svn/trunk/ ${ADOREFOLDER}
  fi
  echo "Please restart ADORE to make sure all changes are in effect."
 fi 
else
 echo "Latest version is already installed."
fi
}

function test1(){
wget http://adore-doris.googlecode.com/files/test1-r2.tar.gz
gunzip test1-r*.tar.gz
archive extract test1-r*
settings load
coarseorb;coarsecorr;fine;coregpm;resample;interfero;comprefpha;subtrrefpha;coherence
bold "Please check to see if the results match. You should see OK after the filenames."
md5sum -c 1393_21066.md5
}

function checkProductSize(){
 local filename resfile format numpixels numlines 
 local fileOnDisk unitSize calculatedSize wrongSize
 wrongSize=false
 call "(filename resfile format numpixels numlines)=dorisProcess2OutputFile ${1};"
 fileOnDisk=`fileSize ${filename}`;
 unitSize=`formatBytes ${format}`;
 calculatedSize=$(( ${unitSize} * ${numpixels} * ${numlines} ))
 if [ ${fileOnDisk} -ne ${calculatedSize} ]; then
   error "Data product for ${1} has a different size than expected."
   error "Expected Size: ${calculatedSize}  File Size: ${fileOnDisk}"
   wrongSize=true
 fi
 if [ ${wrongSize} == true ] && [ "${1}" == "unwrap" ]; then
   #check if piece is set
   local snaphucmd snaphufirstrow snaphufirstcol snaphunrow snaphuncol
   snaphucmd=`history | grep snaphu | grep "piece" | tail -n 1`
   echo "..$snaphucmd.."
   snaphufirstrow=`echo ${snaphucmd#*piece} | cut -d" " -f1` 
   snaphufirstcol=`echo ${snaphucmd#*piece} | cut -d" " -f2`
   snaphunrow=`echo ${snaphucmd#*piece} | cut -d" " -f3` 
   snaphuncol=`echo ${snaphucmd#*piece} | cut -d" " -f4`
   echo "$snaphufirstrow $snaphufirstcol $snaphunrow $snaphuncol" 
   resfilefirstline=`readRes.sh ${resfile} unwrap "First_line (w.r.t. original_master)"`
   resfilelastline=`readRes.sh ${resfile} unwrap "Last_line (w.r.t. original_master)"`
   resfilefirstpixel=`readRes.sh ${resfile} unwrap "First_pixel (w.r.t. original_master)"`
   resfilelastpixel=`readRes.sh ${resfile} unwrap "Last_pixel (w.r.t. original_master)"`
   azMultilook=`readRes.sh ${resfile} unwrap "Multilookfactor_azimuth_direction"`
   rgMultilook=`readRes.sh ${resfile} unwrap "Multilookfactor_azimuth_direction"`
   echo "$resfilefirstline $resfilefirstpixel"
   newfirstline=$(( ${resfilefirstline}+${snaphufirstrow}*${azMultilook} ));
   newlastline=$(( ${resfilefirstline}+(${snaphufirstrow}+${snaphunrow}-1)*${azMultilook} ))
   newfirstpixel=$(( ${resfilefirstpixel}+${snaphufirstcol}*${rgMultilook} ))
   newlastpixel=$(( ${resfilefirstpixel}+(${snaphufirstcol}+${snaphuncol}-1)*${rgMultilook} ))
   numpixels=`echo ${newlastpixel} ${newfirstpixel} ${rgMultilook} | awk 'function ceil(x){ return (x == int(x)) ? x : int(x)+1 } {print ceil(($1-$2+1)/$3)}'`
   numlines=`echo ${newlastline} ${newfirstline} ${azMultilook} | awk 'function ceil(x){ return (x == int(x)) ? x : int(x)+1 } {print ceil(($1-$2+1)/$3)}'`
   modifyRes.sh ${resfile} unwrap "First_line (w.r.t. original_master)"  ${newfirstline}
   modifyRes.sh ${resfile} unwrap "Last_line (w.r.t. original_master)"   ${newlastline}
   modifyRes.sh ${resfile} unwrap "First_pixel (w.r.t. original_master)" ${newfirstpixel}
   modifyRes.sh ${resfile} unwrap "Last_pixel (w.r.t. original_master)"  ${newlastpixel}
   modifyRes.sh ${resfile} unwrap "Number of lines (multilooked)"        ${numlines}
   modifyRes.sh ${resfile} unwrap "Number of pixels (multilooked)"       ${numpixels}
   echo "File size for unwrap adjusted based on last run snaphu --piece command."
 elif [ ${wrongSize} == true ] && [ "${1}" == "m_crop" ]; then
   # check m_dbow
   if [ "${m_dbow}" == "0 0 0 0" ] && [ "${m_dbow_geo}" == "0 0 0 0" ]; then
     #if both unset, then read m_readfiles
     numlines=`readRes.sh ${m_resfile} readfiles "Number_of_lines_original"`
     numpixels=`readRes.sh ${m_resfile} readfiles "Number_of_pixels_original"`

     modifyRes.sh ${m_resfile} crop "First_line (w.r.t. original_image)" 1
     modifyRes.sh ${m_resfile} crop "Last_line (w.r.t. original_image)" $numlines
     modifyRes.sh ${m_resfile} crop "First_pixel (w.r.t. original_image)" 1
     modifyRes.sh ${m_resfile} crop "Last_pixel (w.r.t. original_image)" $numpixels
     modifyRes.sh ${m_resfile} crop "Number of lines (non-multilooked)" $numlines
     modifyRes.sh ${m_resfile} crop "Number of pixels (non-multilooked)" $numpixels
   else
     echo "Please correct filesize manually."
   fi
 elif [ ${wrongSize} == true ]; then
   echo "Please correct filesize manually."
 else
   echo "File size matches the result file."
 fi 
}

#MAIN FUNCTION
if [ "${1}" == "-p" ]; then
 shift 
 checkProcessFlag "${@}"
elif [ "${1}" == "-j" ]; then
 shift
 checkJobStatus "${1}"
 return $?
elif [ "${1}" == "setup" ];then
 shift 
 checkSetup "${@}"
elif [ "${1}" == "updates" ]; then
 shift 
 checkUpdates 
elif [ "${1}" == "productSize" ]; then
 shift
 checkProductSize "${@}"
else
 listProcessFlagsFromResultFiles "$@"
fi 

